const express = require('express');

const Admin = require('../modules/Admin');
const admin = express.Router();

admin.get('/login', (req, res) => {
    res.render('admin/login');
});

admin.post('/login', async(req, res) => {
    const { adminname, password } = req.body;

    // 后台验证表单数据是否为空
    if (adminname.trim().length == 0 || password.trim().length == 0) {
        return res.render('admin/error', { errtype: 'rate-half', message: '登陆的账户或密码错误,请重新登陆！' });
    }

    // 从数据库中查找请求表单中的帐户名  有则返回对象  没有则返回空
    const admin = await Admin.findOne({ adminname });
    /* 查看管理员的账号和密码 */
    console.log(admin);
    if (admin) {
        if (admin.password == password) {
            res.render('admin/index');
        } else {
            return res.render('admin/error', { errtype: 'rate-half', message: '登陆的账户或密码错误,请重新登陆！' });
        }
    } else {
        return res.render('admin/error', { errtype: 'rate-half', message: '登陆的账户或密码错误,请重新登陆！' });
    }
})

admin.get('/role', (req, res) => {
    res.render('admin/city');
})

module.exports = admin